﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SkiaSharp;

namespace netcore_comm.JWT
{
    public class ValidateCodeHelper
    {
        /// <summary>
        /// 验证码的最大长度
        /// </summary>
        public int MaxLength
        {
            get { return 10; }
        }
        /// <summary>
        /// 验证码的最小长度
        /// </summary>
        public int MinLength
        {
            get { return 1; }
        }
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="length">指定验证码的长度</param>
        /// <returns></returns>
        public string CreateValidateCode(int length)
        {
            int[] randMembers = new int[length];
            int[] validateNums = new int[length];
            string validateNumberStr = "";
            //生成起始序列值
            int seekSeek = unchecked((int)DateTime.Now.Ticks);
            Random seekRand = new Random(seekSeek);
            int beginSeek = seekRand.Next(0, int.MaxValue - length * 10000);
            int[] seeks = new int[length];
            for (int i = 0; i < length; i++)
            {
                beginSeek += 10000;
                seeks[i] = beginSeek;
            }
            //生成随机数字
            for (int i = 0; i < length; i++)
            {
                Random rand = new Random(seeks[i]);
                int pownum = 1 * (int)Math.Pow(10, length);
                randMembers[i] = rand.Next(pownum, int.MaxValue);
            }
            //抽取随机数字
            for (int i = 0; i < length; i++)
            {
                string numStr = randMembers[i].ToString();
                int numLength = numStr.Length;
                Random rand = new Random();
                int numPosition = rand.Next(0, numLength - 1);
                validateNums[i] = int.Parse(numStr.Substring(numPosition, 1));
            }
            //生成验证码
            for (int i = 0; i < length; i++)
            {
                validateNumberStr += validateNums[i].ToString();
            }
            return validateNumberStr;
        }


        /// <summary>
        /// 创建验证码的图片
        /// </summary>
        /// <param name="containsPage">要输出到的page对象</param>
        /// <param name="validateNum">验证码</param>
        public byte[] CreateValidateGraphic(string captchaText)
        {
            Random _random = new Random();
            try
            {
                int width = 200;
                int height = 50;
                using var surface = SKSurface.Create(new SKImageInfo(width, height));
                var canvas = surface.Canvas;

                // 1. 绘制背景（渐变色）
                using (var paint = new SKPaint())
                {
                    paint.Shader = SKShader.CreateLinearGradient(
                        new SKPoint(0, 0),
                        new SKPoint(width, height),
                        new[] { SKColors.LightBlue, SKColors.LightYellow },
                        null,
                        SKShaderTileMode.Clamp);
                    canvas.DrawRect(0, 0, width, height, paint);
                }

                // 2. 绘制干扰线
                for (int i = 0; i < 5; i++)
                {
                    canvas.DrawLine(
                        _random.Next(width), _random.Next(height),
                        _random.Next(width), _random.Next(height),
                        new SKPaint { Color = SKColors.Gray, StrokeWidth = 1 });
                }

                // 3. 绘制验证码文本（随机旋转和颜色）
                float x = 15;
                foreach (char c in captchaText)
                {
                    using var textPaint = new SKPaint
                    {
                        Color = new SKColor(
                            (byte)_random.Next(150, 255),
                            (byte)_random.Next(150, 255),
                            (byte)_random.Next(150, 255)),
                        TextSize = 30 + _random.Next(-5, 5),
                        Typeface = SKTypeface.FromFamilyName("DejaVu Sans", SKFontStyle.Bold)
                    };

                    canvas.Save();
                    canvas.Translate(x, height / 2 + _random.Next(-10, 10));
                    canvas.RotateDegrees(_random.Next(-15, 15));
                    canvas.DrawText(c.ToString(), 0, 0, textPaint);
                    canvas.Restore();

                    x += width / captchaText.Length;
                }

                // 4. 添加噪点
                for (int i = 0; i < 100; i++)
                {
                    canvas.DrawPoint(
                        _random.Next(width), _random.Next(height),
                        new SKPaint { Color = SKColors.Black });
                }

                // 5. 输出为 PNG
                using var image = surface.Snapshot();
                using var data = image.Encode(SKEncodedImageFormat.Png, 100);
                return data.ToArray();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 得到验证码图片的长度
        /// </summary>
        /// <param name="validateNumLength">验证码的长度</param>
        /// <returns></returns>
        public static int GetImageWidth(int validateNumLength)
        {
            return (int)(validateNumLength * 20.0);
        }

        /// <summary>
        /// 得到验证码的高度
        /// </summary>
        /// <returns></returns>
        public static double GetImageHeight()
        {
            return 40.0;
        }
    }
}
